package com.wnhz.work.yz.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseLGAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.AddressBean;
import com.wnhz.work.yz.bean.FitmentBean;
import com.wnhz.work.yz.utils.SystemUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.OrderTime;
import com.wnhz.work.yz.view.SwitchView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.wnhz.work.yz.R.id.holder;
import static com.wnhz.work.yz.R.id.remark;

/**
 * ---立即购买  结算
 */
public class SettleAccounts2Activity extends BaseActivity implements View.OnClickListener, SwitchView.OnStateChangedListener {
    private static final String TAG = "SettleAccounts2Activity";

    private BaseLGAdapter<FitmentBean> adapter;
    private List<FitmentBean> list = new ArrayList<>();
    private ListView listView;
    private SwitchView sw_need, sw_service;
    private View include_address, include_noAddress;
    private TextView tv_name, tv_phone, tv_address;
    private ImageView shopping_img;
    private RelativeLayout rl_invoice;
    private TextView invoice_tv, title_tv, material, tv_price, number_tv;
    private static final int CODE_ADDRESS = 111;
    private static final int CODE_INVOICE = 112;
    private String addrId = "";
    private TextView pay_money;
    private int isOpened = 0;
    private String invoiceId = "";
    private TextView title;
    private String packageId;
    private String skuId;
    private String nums;
    private String packageName;
    private String img;
    private String Sku_des;
    private String price;
    private String money;
    private String remark;
    private String type;
    private TextView pay_type_message;
    private TextView all_money;
    private String payId = "";

    private String install = "";
    private String need = "0";
    private RelativeLayout rl_message;

    private int textColorLi, textColorNor;
    private int BackColorLi, BackColorNor;
    private TextView pay_type1, pay_type2, pay_type3, tv_install_fee;
    private EditText et_car, et_send, et_remark;
    private RelativeLayout rl_service;

    private TextView freight_tv;
    private int payType = -1;
    private Double allPrice;
    private String weight;
    private static final int CODE_PAY = 379;
    private TextView tv_time;
    private TextView tv_pay_type;
    private String package_cate;

    private TextView tv_invoice;
    private String install_fee;


    private List<FitmentBean> beanList;

    public static Intent createIntent(Context context, String packageId, String skuId, String nums, String packageName, String Sku_des, String img, String remark, String money, String type, String weight, String package_cate, String install_fee) {
        Intent intent = new Intent(context, SettleAccounts2Activity.class);
        intent.putExtra("packageId", packageId);
        intent.putExtra("skuId", skuId);
        intent.putExtra("nums", nums);
        intent.putExtra("packageName", packageName);
        intent.putExtra("Sku_des", Sku_des);
        intent.putExtra("img", img);
        intent.putExtra("remark", remark);
        intent.putExtra("money", money);
        intent.putExtra("type", type);
        intent.putExtra("weight", weight);
        intent.putExtra("package_cate", package_cate);
        intent.putExtra("install_fee", install_fee);
        return intent;
    }

    private void parseIntent() {
        Intent intent = getIntent();
        packageId = intent.getStringExtra("packageId");
        skuId = intent.getStringExtra("skuId");
        nums = intent.getStringExtra("nums");
        packageName = intent.getStringExtra("packageName");

        Sku_des = intent.getStringExtra("Sku_des");
        img = intent.getStringExtra("img");
        remark = intent.getStringExtra("remark");
        money = intent.getStringExtra("money");
        type = intent.getStringExtra("type");
        weight = intent.getStringExtra("weight");
        package_cate = intent.getStringExtra("package_cate");
        install_fee = intent.getStringExtra("install_fee");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settle_accounts2);
        parseIntent();

        allPrice = Double.valueOf(money) * Double.valueOf(nums);
        rl_message = (RelativeLayout) findViewById(R.id.rl_message);
        textColorLi = getResources().getColor(R.color.main_color);
        textColorNor = getResources().getColor(R.color.text);
        BackColorLi = R.drawable.button_bg_pick;
        BackColorNor = R.drawable.btn_white;

        tv_invoice = (TextView) findViewById(R.id.tv_invoice);

        initTitle();

        findViewById(R.id.rl_pay_type).setOnClickListener(this);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_pay_type = (TextView) findViewById(R.id.tv_pay_type);

        sw_service = (SwitchView) findViewById(R.id.sw_service);//服务费
        sw_need = (SwitchView) findViewById(R.id.sw_need);//发票信息

        sw_service = (SwitchView) findViewById(R.id.sw_service);
        sw_service.setOpened(false);
        sw_service.setOnStateChangedListener(this);

        sw_need = (SwitchView) findViewById(R.id.sw_need);
        sw_need.setOpened(false);
        sw_need.setOnStateChangedListener(this);


        listView = (ListView) findViewById(R.id.listView);
        findViewById(R.id.rl_time).setOnClickListener(this);

        et_car = (EditText) findViewById(R.id.et_car);
        et_send = (EditText) findViewById(R.id.et_send);
        et_remark = (EditText) findViewById(R.id.et_remark);
        rl_message.setOnClickListener(this);


        rl_service = (RelativeLayout) findViewById(R.id.rl_service);
        rl_service.setOnClickListener(this);
        /**
         * 判断是否有地址选择显示隐藏的布局
         */
        include_address = findViewById(R.id.include_choose_address);//有地址
        include_noAddress = findViewById(R.id.include_choose_noAddress);//无收货地址

        include_address.setOnClickListener(this);
        include_noAddress.setOnClickListener(this);

        include_address.setVisibility(View.GONE);// TODO  暂时设为不可见

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_address = (TextView) findViewById(R.id.tv_address);
        pay_money = (TextView) findViewById(R.id.pay_money);

        shopping_img = (ImageView) findViewById(R.id.shopping_img);
        title_tv = (TextView) findViewById(R.id.title_tv);
        material = (TextView) findViewById(R.id.material);
        tv_price = (TextView) findViewById(R.id.tv_price);
        number_tv = (TextView) findViewById(R.id.number_tv);

        pay_type_message = (TextView) findViewById(R.id.pay_type_message);
        tv_install_fee = (TextView) findViewById(R.id.tv_install_fee);

        freight_tv = (TextView) findViewById(R.id.freight_tv);

        all_money = (TextView) findViewById(R.id.all_money);
        all_money.setText("¥" + allPrice);
        pay_money.setText("" + allPrice);
        tv_install_fee.setText("¥" + install_fee);

        Glide.with(this).load(img).error(R.mipmap.img_chanpinfenlei1).crossFade().into(shopping_img);
        title_tv.setText(packageName);
        material.setText("" + Sku_des);
        tv_price.setText("￥" + money);
        number_tv.setText("x" + nums);

        pay_type1 = (TextView) findViewById(R.id.pay_type1);
        pay_type2 = (TextView) findViewById(R.id.pay_type2);
        pay_type3 = (TextView) findViewById(R.id.pay_type3);
        pay_type1.setOnClickListener(this);
        pay_type2.setOnClickListener(this);
        pay_type3.setOnClickListener(this);

        pay_type_message.setText("注：线上支付是购买总费用加物流(配送)费用");
    }

    private void initTitle() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("结算");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.tv_true).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.pay_type1:
                pay_type1.setTextColor(textColorLi);
                pay_type2.setTextColor(textColorNor);
                pay_type3.setTextColor(textColorNor);
                pay_type1.setBackgroundResource(BackColorLi);
                pay_type2.setBackgroundResource(BackColorNor);
                pay_type3.setBackgroundResource(BackColorNor);
                payType = 0;
                pay_type_message.setText("注：线上支付是购买总费用加物流(配送)费用");
                freight_tv.setText("¥" + moneyInfo);
                double allMoney = Double.parseDouble(pay_money.getText().toString()) + moneyInfo;
                pay_money.setText("" + allMoney);

                break;
            case R.id.pay_type2:
                pay_type1.setTextColor(textColorNor);
                pay_type2.setTextColor(textColorLi);
                pay_type3.setTextColor(textColorNor);
                pay_type1.setBackgroundResource(BackColorNor);
                pay_type2.setBackgroundResource(BackColorLi);
                pay_type3.setBackgroundResource(BackColorNor);
                payType = 1;
                pay_type_message.setText("注：只需支付商品总费用，快递费到付");
                freight_tv.setText("到付");
                pay_money.setText("" + Double.parseDouble("" + allPrice));
                break;
            case R.id.pay_type3:
                pay_type1.setTextColor(textColorNor);
                pay_type2.setTextColor(textColorNor);
                pay_type3.setTextColor(textColorLi);
                pay_type1.setBackgroundResource(BackColorNor);
                pay_type2.setBackgroundResource(BackColorNor);
                pay_type3.setBackgroundResource(BackColorLi);
                payType = 2;
                pay_type_message.setText("注：只需支付商品总费用，商品由买家自提");
                freight_tv.setText("自提");
                pay_money.setText("" + Double.parseDouble("" + allPrice));
                break;

            //立即购买  支付
            case R.id.tv_true:

                if (addrId.equals("")) {
                    MyToast("请选择收货地址");
                    return;
                }

                if (tv_time.getText().toString().equals("请选择")) {
                    MyToast("请选择配送时间");
                    return;
                }

                if (tv_pay_type.getText().toString().equals("请选择")) {
                    MyToast("请选择付款方式");
                    return;
                }

                if (need.equals("1") && invoiceId.equals("")) {
                    MyToast("请选择发票信息");
                    return;
                }

                if (payType == -1) {
                    MyToast("请选择支付方式");
                    return;
                }

                commitOrder();
                break;

            //时间
            case R.id.rl_time:
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();//取时间
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(calendar.DATE, 8);//把日期往后增加一天.整数往后推,负数往前移动
                date = calendar.getTime();   //这个时间就是日期往后推一天的结果
//                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(date);
                OrderTime dataPicker = new OrderTime(SettleAccounts2Activity.this);
                dataPicker.selectDateDialog(tv_time, str, "start");

                String todayTime = tv_time.getText().toString();
                break;

            //发票信息
            case R.id.rl_message:
                intent = new Intent(this, SelectFapiaoActivity.class);
                startActivityForResult(intent, CODE_INVOICE);
                break;

            //有地址，前去修改
            case R.id.include_choose_address:
                intent = new Intent(this, ChooseAddressActivity.class);
                startActivityForResult(intent, CODE_ADDRESS);
                break;

            //无地址，添加收货地址
            case R.id.include_choose_noAddress:
                intent = new Intent(this, ChooseAddressActivity.class);
                startActivityForResult(intent, CODE_ADDRESS);
                break;

            //付款方式
            case R.id.rl_pay_type:
                intent = new Intent(this, PayTypeActivity.class);
                intent.putExtra("name", package_cate);
                intent.putExtra("from", "2");
                startActivityForResult(intent, CODE_PAY);
                break;
            default:
                break;
        }
    }

    private void commitOrder() {
        showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("package_id", packageId);
        map.put("sku_id", skuId);
        map.put("remark", et_remark.getText().toString());
        map.put("nums", "" + nums);
        map.put("type", "" + type);
        map.put("addressId", addrId);
        map.put("deliver_time", tv_time.getText().toString());
        map.put("deliver_requir", et_car.getText().toString());
        map.put("vehicle_requir", et_send.getText().toString());
        map.put("if_install", install);
        map.put("install_fee", install_fee);
        map.put("express_fee", moneyInfo);
        map.put("pay_way", payId);
        map.put("other_type", payType);

        map.put("equipment", "android");
        map.put("version", "" + SystemUtils.getVersionName(SettleAccounts2Activity.this));

        /**
         * deliver_time  配送时间
         deliver_requir 发货要求
         vehicle_requir 车辆要求
         if_install 是否安装（0和1）
         install_fee 安装费
         express_fee 运费
         pay_way
         other_type

         */

        XUtil.Post(Url.LIJIBUY, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("=== 立即下班  购买==", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    if ("1".equals(res)) {
                        JSONObject jsonObject1 = jsonObject.optJSONObject("info");
                        String order_no = jsonObject1.optString("order_no");
                        String msg = jsonObject1.optString("msg");
                        MyToast(msg);
                        String money = pay_money.getText().toString();
                        Intent intent = new Intent(SettleAccounts2Activity.this, ChoosePayActivity.class);
                        intent.putExtra("order_no", order_no);
                        intent.putExtra("money", money);
                        startActivity(intent);
                        finish();
                    } else {
                        String info = jsonObject.optString("info");
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });

    }

    private void showOrHidePickLayout1(boolean isNeedToPick) {

        if (isNeedToPick) {
            rl_service.setVisibility(View.VISIBLE);
        } else {
            rl_service.setVisibility(View.GONE);
        }
    }

    private void showOrHidePickLayout2(boolean isNeedToPick) {

        if (isNeedToPick) {
            rl_message.setVisibility(View.VISIBLE);
        } else {
            rl_message.setVisibility(View.GONE);
        }
    }

    @Override
    public void toggleToOn(View view) {
        switch (view.getId()) {
            //服务费
            case R.id.sw_service:
                sw_service.setOpened(true);
                showOrHidePickLayout1(true);
                install = "1";

                all_money.setText("¥" + (allPrice + Double.parseDouble(install_fee)));
                pay_money.setText("" + (allPrice + Double.parseDouble(install_fee)));
                break;

            //发票信息
            case R.id.sw_need:
                sw_need.setOpened(true);
                showOrHidePickLayout2(true);
                need = "1";
                break;

            default:
                break;
        }
    }

    @Override
    public void toggleToOff(View view) {
        switch (view.getId()) {
            case R.id.sw_service:
                sw_service.setOpened(false);
                showOrHidePickLayout1(false);
                install = "0";

                all_money.setText("¥" + allPrice);
                pay_money.setText("" + allPrice);
                break;

            case R.id.sw_need:
                sw_need.setOpened(false);
                showOrHidePickLayout2(false);
                need = "0";
                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {

            //地址回调
            case CODE_ADDRESS:
                if (resultCode == RESULT_OK) {
                    if (null != data) {
                        AddressBean addressBean = (AddressBean) data.getSerializableExtra("addressBean");
                        include_address.setVisibility(View.VISIBLE);
                        include_noAddress.setVisibility(View.GONE);
                        String province = addressBean.getProvince();
                        String city = addressBean.getCity();
                        String district = addressBean.getDistrict();
                        String place = addressBean.getPlace();
                        String addr = province + city + district + place;
                        tv_name.setText(addressBean.getConsignee());
                        tv_phone.setText(addressBean.getTelephone());
                        tv_address.setText(addr);
                        addrId = addressBean.getAddress_id();

                        upfee(addrId);
                    }
                }
                break;

            //发票回调
            case CODE_INVOICE:
                if (resultCode == RESULT_OK) {
                    String name = data.getStringExtra("name");
                    invoiceId = data.getStringExtra("id");
                    tv_invoice.setText(name + "");
                }
                Log.e("-----", "type" + type);
                break;

            //付款方式回调
            case CODE_PAY:
                if (resultCode == RESULT_OK) {
                    if (null != data) {
                        String name = data.getStringExtra("pay");
                        payId = data.getStringExtra("payId");
                        tv_pay_type.setText(name);
                    }
                }
                break;

            default:
                break;
        }
    }

    private double moneyInfo = 0;
    private boolean isTure;

    private void upfee(final String addrId) {
        showDialog();
        Map<String, Object> map = new HashMap<>();

        map.put("addressId", addrId);
        map.put("weight", weight + "");
        XUtil.Post(Url.ORDER_CHANGEEXPRESSFEE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                Log.i(TAG, addrId + "onSuccess: weight= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");

                    double allMoney = allPrice;
                    if ("1".equals(res)) {
                        moneyInfo = Double.parseDouble(info);
                        switch (payType) {
                            case 0:
                                freight_tv.setText("¥" + moneyInfo);
                                allMoney = Double.parseDouble("" + allPrice) + moneyInfo;
                                break;
                            case 1:
                                allMoney = Double.parseDouble("" + allPrice);
                                freight_tv.setText("到付");
                                break;
                            case 2:
                                allMoney = Double.parseDouble("" + allPrice);
                                freight_tv.setText("自提");
                                break;
                        }
                        pay_money.setText("" + allMoney);
                    } else {
                        MyToast(info);
                        isTure = false;
                        freight_tv.setText("¥0.0");
                        pay_money.setText("" + allMoney);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }
}
